package configure

import (
	_ "embed"
	"encoding/json"
	"gitee.com/kristas/booting-go/framework/common/util/config_merge"
	"gitee.com/kristas/booting-go/framework/common/util/file"
	"gitee.com/kristas/booting-go/framework/common/util/lang"
	"github.com/fsnotify/fsnotify"
	"gopkg.in/yaml.v3"
	"log"
	"os"
)

//go:embed config_source.json
var embedSource []byte

type localConfigLoader struct {
}

func (l *localConfigLoader) Load(environment string) ([]byte, error) {
	var configMap = make(map[string]interface{})
	configPaths := localConfigOrders(environment)
	for _, path := range configPaths {
		if !file.Exist(path) {
			continue
		}
		bytes, err := os.ReadFile(path)
		if err != nil {
			return nil, err
		}
		var tmp = make(map[string]interface{})
		err = yaml.Unmarshal(bytes, tmp)
		if err != nil {
			panic(err)
		}
		configMap = config_merge.MergeMap(configMap, tmp)
	}
	bytes, err := yaml.Marshal(configMap)
	if err != nil {
		return nil, err
	}
	return bytes, nil
}

func (l *localConfigLoader) RegisterListener(environment string) error {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		return err
	}
	defer watcher.Close()

	done := make(chan bool)
	go func() {
		for {
			select {
			case event, ok := <-watcher.Events:
				if !ok {
					return
				}
				if event.Op&fsnotify.Write == fsnotify.Write {
					log.Println("config change:", event.Name)
					bytes, err := os.ReadFile(event.Name)
					if err != nil {
						continue
					}
					SetConfig(bytes)
					UpdateConfig()
					log.Println("config update!")
				}
			case err, ok := <-watcher.Errors:
				if !ok {
					return
				}
				log.Println("error:", err)
			}
		}
	}()
	orders := localConfigOrders(environment)
	for _, order := range orders {
		if !file.Exist(order) {
			continue
		}
		err = watcher.Add(order)
		if err != nil {
			return err
		}
	}
	<-done
	return nil
}

type configSource struct {
	In    []string `json:"in"`
	Names []string `json:"names"`
}

func localConfigOrders(environment string) []string {
	var cs configSource
	err := json.Unmarshal(embedSource, &cs)
	if err != nil {
		panic(err)
	}
	var sources []string
	for _, in := range cs.In {
		for _, name := range cs.Names {
			sources = append(sources, lang.NewString(in).Concat(name).ReplaceAll("[env]", environment).String())
		}
	}
	return sources
}
